package com.software.levelupserver.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class JwtUtil {
    @Value("${kansha.wokao}")
    private String secrete;

    public String createJwt(String user, List<String> authList){
        Date issDate = new Date();
        Date expiredDate = new Date(issDate.getTime()+1000*60*60*2);
        Map<String,Object> headerClaims = new HashMap<>();
        headerClaims.put("alg","HS256");
        headerClaims.put("typ","JWT");
        return JWT.create().withHeader(headerClaims)
                .withIssuer("shabi")
                .withIssuedAt(issDate)
                .withExpiresAt(expiredDate)
                .withClaim("user",user)
                .withClaim("authList",authList)
                .sign(Algorithm.HMAC256(secrete));
    }
    public void verifyJwt(String jwt){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secrete)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
    }
    public String getUserFromJwt(String jwt){
        try{
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secrete)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
            return decodedJWT.getClaim("user").asString();
        }catch (Exception e){
            return "";
        }
    }
    public List<String> getUserAuthFromJwt(String jwt){
        try{
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secrete)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
            return decodedJWT.getClaim("userAuth").asList(String.class);
        }catch (Exception e){
            return null;
        }
    }
}

